// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'zbdc-6gavbhj633c62e27'
})
const db = cloud.database();
exports.main = async (event, context) => {
let wordList = []
// 这段可以查询显示两个表的数据
let cet4 = await db.collection('CET4').where({
  content: event.content,
  _id: event.id
}).get()
let cet6 = await db.collection('CET6').where({
  headWord: event.content,
  _id: event.id
}).get()
let kaoyan = await db.collection('KAOYAN').where({
    headWord: event.content,
    _id: event.id
  })
  .get()

// 采用同步内执行循环的方法，可以防止循环的数据过大，还没有执行结束，就执行后续过程
new Promise(() => {
  cet4.data.forEach(item => {
    item.type = 'cet4'
  });
  cet6.data.forEach(item => {
    // 拼接samples
    let sms = item.content.word.content.sentence ? item.content.word.content.sentence.sentences ? item.content.word.content.sentence.sentences : [] : []
    sms = sms.map((itm, index) => {
      return itm.sCn.concat('\n' + itm.sContent) // 拼接
    }).join('\n')
    // 拼接phrase
    let phr = item.content.word.content.phrase ? item.content.word.content.phrase.phrases ? item.content.word.content.phrase.phrases : [] : []
    phr = phr.slice(0, 3).map((itm, idx) => {
      return itm.pCn.concat('\n' + itm.pContent+';')
    }).join('\n')
    // 拼接definition
    let def = item.content.word.content.trans
    def = def.map((itm, idx) => {
      return itm.pos.concat('.'+itm.tranCn)
    }).join('\n')
    console.log(def)
    wordList.push({ // 组成集合
      _id: item._id,
      content: item.headWord,
      type: 'cet6',
      pron: item.content.word.content.phone || item.content.word.content.usphone,
      definition: def, // 要拼
      samples: sms, // 要拼
      phrase: phr, // 要拼
      lyric:item.lyric?item.lyric:'',
      address:item.address?item.address:''
    })
  })
  kaoyan.data.forEach(item => {
    // 拼接samples
    let sms = item.content.word.content.sentence ? item.content.word.content.sentence.sentences ? item.content.word.content.sentence.sentences : [] : []
    sms = sms.map((itm, index) => {
      return itm.sCn.concat('\n' + itm.sContent) // 拼接
    }).join('\n')
    // 拼接phrase
    let phr = item.content.word.content.phrase ? item.content.word.content.phrase.phrases ? item.content.word.content.phrase.phrases : [] : []
    phr = phr.slice(0, 3).map((itm, idx) => {
      return itm.pCn.concat('\n' + itm.pContent+';')
    }).join('\n')
    // 拼接definition
    let def = item.content.word.content.trans
    def = def.map((itm, idx) => {
      return itm.pos.concat('.'+itm.tranCn)
    }).join('\n')
    console.log(def)
    wordList.push({ // 组成集合
      _id: item._id,
      id:item.wordRank,
      content: item.headWord,
      type: 'PG',
      pron: item.content.word.content.phone || item.content.word.content.usphone,
      definition: def, // 要拼
      samples: sms, // 要拼
      phrase: phr, // 要拼
      lyric:item.lyric?item.lyric:'',
      address:item.address?item.address:''
    })
  })
})
return [...cet4.data, ...wordList]
}